package com.fruit.common;

import org.apache.commons.lang3.StringUtils;

import com.fruit.pojo.user.UserWeChat;
import com.fruit.util.HttpClientManagerT;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

/**
 * 微信相关接口访问
 * @author Administrator
 * @version 2017.12.01 11:40
 */
@Slf4j
public final class WeChatUtils {
	private WeChatUtils() { };
	/**
	 * 刷新微信用户token
	 * @param appid appid
	 * @param secret secret
	 * @param code code
	 * @return JSONObject
	 */
	public static JSONObject getWxJsApiToken(String appid, String secret, String code) {
		log.info("获取Token开始 appid={},secret={},code={}", appid, secret, code);
		JSONObject json = null;
		if (!StringUtils.isEmpty(appid) && !StringUtils.isEmpty(secret)  && !StringUtils.isEmpty(code)) {
			try {
				StringBuffer url = new StringBuffer();
				url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=").append(appid);
				url.append("&secret=").append(secret).append("&code=").append(code).append("&grant_type=authorization_code");
				log.info("获取Token的url{}", url.toString());
				String res = HttpClientManagerT.getData(url.toString());
				log.info("获取Token结果{}", res);
				
				if (res == null) {
					log.error("调用获取Token失败!");
					return null;
				}
				JSONObject tokenjson = JSONObject.fromObject(res);
				if (tokenjson.get("errcode") != null) {
					log.error("获取Token失败errcode{}", tokenjson.get("errcode"));
					return null;
				} else {
					json = tokenjson;
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("获取Token异常！{}", e);
				return null;
			}
		} else {
			log.error("获取Token入参不合法 appid={},secret={},code={}", appid, secret, code);
		}
		log.info("获取Token结束");
		return json;
	}
	
	/**
	 * 刷新微信用户token
	 * @param refreshToken refreshToken
	 * @param appid appid
	 * @return JSONObject
	 */
	public static JSONObject getWxJsApiRefreshToken(String refreshToken, String appid) {
		log.info("获取refreshToken开始{} appid {}", refreshToken, appid);
		JSONObject json = null;
		if (!StringUtils.isEmpty(refreshToken) && !StringUtils.isEmpty(refreshToken)) {
			try {
				StringBuffer url = new StringBuffer();
				url.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=").append(appid);
				url.append("&grant_type=refresh_token&refresh_token=").append(refreshToken);
				
				String res = HttpClientManagerT.getData(url.toString());
				log.info("获取refreshToken结果{}", res);
				
				if (res == null) {
					log.error("调用刷新微信token失败!");
					return null;
				}
				JSONObject refreshTokenjson = JSONObject.fromObject(res);
				if (refreshTokenjson.get("errcode") != null) {
					log.error("调用刷新微信token失败errcode{}", refreshTokenjson.get("errcode"));
					return null;
				} else {
					json = refreshTokenjson;
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("微信刷新令牌异常！{}", e);
				return null;
			}
		}
		log.info("获取refreshToken结束");
		return json;
	}
	
	/**
	 * 获取微信用户信息
	 * @param openid 用户标识
	 * @param accessToken 令牌
	 * @return WeChatUser
	 */
	public static UserWeChat getWxJsApiUserInfo(String openid, String accessToken) {
		log.info("获取微信用户信息accessToken{} openid", accessToken, openid);
		UserWeChat userWeChat = null;
		if (!StringUtils.isEmpty(accessToken) && !StringUtils.isEmpty(openid)) {
			try {
				StringBuffer url = new StringBuffer();
				url.append("https://api.weixin.qq.com/sns/userinfo?access_token=").append(accessToken)
				.append("&openid=").append(openid).append("&lang=zh_CN");
				
				log.info("获取微信用户信息结果url{}", url.toString());
				String res = HttpClientManagerT.getData(url.toString());
				log.info("获取微信用户信息结果{}", res);
				
				if (res == null) {
					log.error("调用微信用户信息失败!");
					return null;
				}
				JSONObject userJson = JSONObject.fromObject(res);
				if (userJson.get("errcode") != null) {
					log.error("调用微信用户信息失败errcode{}", userJson.get("errcode"));
					return null;
				} else {
					userWeChat = (UserWeChat) JSONObject.toBean(userJson, UserWeChat.class);
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("获取微信用户信息异常!{}", e);
				return null;
			}
		}
		log.info("获取微信用户信息结束");
		return userWeChat;
	}
	
	/**
	 * 校验微信用户token
	 * @param openid 用户标识
	 * @param accessToken 令牌
	 * @return true or false
	 */
	public static boolean getWxJsApiCheckToken(String openid, String accessToken) {
		log.info("校验accessToken开始{} openid {}", accessToken, openid);
		boolean result = false;
		if (!StringUtils.isEmpty(accessToken) && !StringUtils.isEmpty(openid)) {
			try {
				StringBuffer url = new StringBuffer();
				url.append("https://api.weixin.qq.com/sns/auth?access_token=").append(accessToken);
				url.append("&openid=").append(openid);
				
				String res = HttpClientManagerT.getData(url.toString());
				log.info("校验accessToken结果{}", res);
				
				if (res == null) {
					log.error("校验accessToken调用失败!");
					return result;
				}
				JSONObject json = JSONObject.fromObject(res);
				String errcode = json.getString("errcode");
				log.info("校验accessToken结果errcode的值{}", errcode);
				if ("0".equals(errcode)) {
					result = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("微信校验令牌失异常!{}", e);
				return result;
			}
		}
		log.info("校验accessToken结束{}", result);
		return result;
	}
	/**
	 * 获取微信公众号jsapi_ticket
	 * @param accessToken accessToken
	 * @return JSONObject
	 */
	public static JSONObject getWxJsApiJsTicket(String accessToken) {
		log.info("获取微信JsToken{}", accessToken);
		JSONObject json = null;
		if (!StringUtils.isEmpty(accessToken)) {
			try {
				StringBuffer url = new StringBuffer();
				url.append("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=").append(accessToken)
				.append("&type=jsapi");
				
				log.info("获取微信JsToken结果url{}", url.toString());
				String res = HttpClientManagerT.getData(url.toString());
				log.info("获取微信JsToken结果{}", res);
				
				if (res == null) {
					log.error("获取微信JsToken失败!");
					return null;
				}
				JSONObject usjson = JSONObject.fromObject(res);
				if ("0".equals(usjson.get("errcode").toString())) {
					json = usjson;
				} else {
					log.error("获取微信JsToken errcode{}", usjson.get("errcode"));
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("获取微信JsToken异常!{}", e);
				return null;
			}
		}
		log.info("获取微信JsToken结束");
		return json;
	}
	
	/**
	 * 获取微信公众号accessToken
	 * @param appid appid
	 * @param secret secret
	 * @return JSONObject
	 */
	public static JSONObject getWxJsApiJsToken(String appid, String secret) {
		log.info("微信公众号accessToken appid={},secret={}", appid, secret);
		JSONObject json = null;
		if (!StringUtils.isEmpty(appid) && !StringUtils.isEmpty(secret)) {
			try {
				StringBuffer url = new StringBuffer();
				url.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=").append(appid)
				.append("&secret=").append(secret);
				
				log.info("微信公众号accessToken结果url{}", url.toString());
				String res = HttpClientManagerT.getData(url.toString());
				log.info("微信公众号accessToken结果{}", res);
				
				if (res == null) {
					log.error("微信公众号accessToken失败!");
					return null;
				}
				JSONObject tokenJson = JSONObject.fromObject(res);
				if (tokenJson.get("errcode") != null) {
					log.error("微信公众号accessToken失败errcode{}", tokenJson.get("errcode"));
					return null;
				} else {
					json = tokenJson;
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("微信公众号accessToken异常!{}", e);
				return null;
			}
		}
		log.info("微信公众号accessToken结束");
		return json;
	}
}
